package jnpf.scheduletask.rest;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import jnpf.base.Pagination;
import jnpf.base.UserInfo;
import jnpf.base.vo.PaginationVO;
import jnpf.scheduletask.config.RegisterAddressConfig;
import jnpf.scheduletask.entity.*;
import jnpf.scheduletask.model.*;
import jnpf.util.JsonUtil;
import jnpf.util.context.SpringContext;
import jnpf.util.wxutil.HttpUtil;
import lombok.extern.slf4j.Slf4j;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

@Slf4j
public class RestScheduleTaskUtil {

    private static RegisterAddressConfig registerAddressConfig;

    static {
        RegisterAddressConfig bean = SpringContext.getBean(RegisterAddressConfig.class);
        if (bean == null) {
            log.error("RegisterAddressConfig Bean未加载成功");
        }
        registerAddressConfig = bean;
    }

    /**
     * 获取执行器列表
     *
     * @return
     */
    public static List<HandlerNameEntity> getHandlerList() {
        String handlerList = cn.hutool.http.HttpUtil.get(registerAddressConfig.getHandle_query_address());
        if (handlerList == null) {
            return new ArrayList<>();
        }
        return JsonUtil.getJsonToList(handlerList, HandlerNameEntity.class);
    }

    /**
     * 通过任务id获取日志列表
     *
     * @param id 任务id
     * @param userInfo
     * @param taskPage 分页参数
     * @return
     */
    public static JSONObject getLogList(String id, UserInfo userInfo, TaskPage taskPage) {
        String param = taskPage.getRunResult() == null ? "&runResult=" : "&runResult=" + taskPage.getRunResult().toString();
        String timeSelect = "";
        if (ObjectUtil.isNotNull(taskPage.getStartTime()) || ObjectUtil.isNotNull(taskPage.getEndTime())) {
            timeSelect = "&startTime=" + taskPage.getStartTime()
                    + "&endTime=" + taskPage.getEndTime();
        }
        JSONObject get = HttpUtil.httpRequest(registerAddressConfig.getLog_query_address() + "/" + id
                        + "?currentPage=" + taskPage.getCurrentPage()
                        + "&pageSize=" + taskPage.getPageSize()
                        + "&sort=" + taskPage.getSort()
                        + "&sidx=" + taskPage.getSidx() + param + timeSelect,
                "POST", JsonUtil.getObjectToString(userInfo), null);
        JSONObject jsonObject = (JSONObject) get.get("data");
        List<TaskLogVO> data = JsonUtil.getJsonToList(jsonObject.get("list"), TaskLogVO.class);
        PaginationVO page = JsonUtil.getJsonToBean(jsonObject.get("pagination"), PaginationVO.class);
        jsonObject.put("list", data);
        jsonObject.put("pagination", page);
        get.put("data", jsonObject);
        return get;
    }

    /**
     * 获取分页数据
     *
     * @param pagination 分页参数
     * @return
     */
    public static JSONObject getList(Pagination pagination, UserInfo userInfo) {
        JSONObject get = null;
        try {
            get = HttpUtil.httpRequest(registerAddressConfig.getTask_list_address()
                            + "?currentPage=" + pagination.getCurrentPage()
                            + "&pageSize=" + pagination.getPageSize()
                            + "&keyword=" + URLEncoder.encode(pagination.getKeyword(), "utf-8"),
                    "POST", JsonUtil.getObjectToString(userInfo), null);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        JSONObject jsonObject = (JSONObject) get.get("data");
        List<TaskVO> data = JsonUtil.getJsonToList(jsonObject.get("list"), TaskVO.class);
        PaginationVO page = JsonUtil.getJsonToBean(jsonObject.get("pagination"), PaginationVO.class);
        jsonObject.put("list", data);
        jsonObject.put("pagination", page);
        get.put("data", jsonObject);
        return get;
    }

    /**
     * 通过任务id获取任务详情
     *
     * @param id 任务id
     * @return
     */
    public static TimeTaskEntity getInfo(String id, UserInfo userInfo) {
        JSONObject get = HttpUtil.httpRequest(registerAddressConfig.getTask_info_address() + "?taskId=" + id,
                "POST", JsonUtil.getObjectToString(userInfo), null);
        return JsonUtil.getJsonToBean(get, TimeTaskEntity.class);
    }

    /**
     * 保存任务调度
     *
     * @param taskCrForm
     * @return
     */
    public static JSONObject create(TaskCrForm taskCrForm) {
        JSONObject get = HttpUtil.httpRequest(registerAddressConfig.getTask_save_address(),
                "POST", JsonUtil.getObjectToString(taskCrForm), null);
        return get;
    }

    /**
     * 日程任务调度
     *
     * @param taskCrForm
     * @return
     */
    public static JSONObject schedule(TaskCrForm taskCrForm) {
        JSONObject get = HttpUtil.httpRequest(registerAddressConfig.getTask_save_address()+"/schedule",
                "POST", JsonUtil.getObjectToString(taskCrForm), null);
        return get;
    }

    /**
     * 修改任务调度
     *
     * @param id
     * @param taskUpForm
     * @return
     */
    public static JSONObject update(String id, TaskUpForm taskUpForm) {
        JSONObject get = HttpUtil.httpRequest(registerAddressConfig.getTask_update_address() + "/" + id,
                "PUT", JsonUtil.getObjectToString(taskUpForm), null);
        return get;
    }

    /**
     * 删除任务调度
     *
     * @param id
     * @return
     */
    public static JSONObject delete(String id, UserInfo userInfo) {
        JSONObject get = HttpUtil.httpRequest(registerAddressConfig.getTask_remove_address() + "/" + id,
                "POST", JsonUtil.getObjectToString(userInfo), null);
        return get;
    }

    /**
     * 启动任务调度
     *
     * @param updateTaskModel
     * @return
     */
    public static JSONObject updateTask(UpdateTaskModel updateTaskModel) {
        JSONObject get = HttpUtil.httpRequest(registerAddressConfig.getTask_startOrRemove_address(),
                "POST", JsonUtil.getObjectToString(updateTaskModel), null);
        return get;
    }


    public static XxlJobInfo getInfoByTaskId(String taskId) {
        JSONObject get = HttpUtil.httpRequest(registerAddressConfig.getJob_info_address() + "?taskId=" + taskId,
                "GET", null, null);
        return JsonUtil.getJsonToBean(get, XxlJobInfo.class);
    }
}
